package org.sardine.aop;

import java.lang.reflect.Method;
import java.util.List;

import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CglibMethodInterceptor implements MethodInterceptor{
	
	private final Logger log = Logger.getLogger(CglibMethodInterceptor.class);
	private ProxySupport support;
	
	public CglibMethodInterceptor(ProxySupport support){
		this.support = support;
	}

	public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
		
		Object returnVal = null;
		MethodInvocation invocation = null;
		
		List<Advice> interceptors = support.getInterceptors();
		
		if(interceptors.isEmpty()){
			returnVal = methodProxy.invokeSuper(proxy, args);
		}else{
			
			log.debug("MethodNamePatterns size is "+support.getMethodNamePatterns().size());
			if(support.getMethodNamePatterns().size()>0){
				if(!matchMethodNamePattern(method)){
					return methodProxy.invokeSuper(proxy, args);
				}
			}
			
			invocation = new CglibMethodInvocation(proxy, method, args, methodProxy, interceptors);
			returnVal = invocation.proceed();
		}
		/*
		System.out.println("--before--");
		returnVal = methodProxy.invokeSuper(proxy, args);
		System.out.println("--after--");*/
		return returnVal;
	}
	
	private boolean matchMethodNamePattern(Method method){
		
		String className = method.getDeclaringClass().getName();
		String methodName = method.getName();
		
		return support.matchMethodNamePattern(className, methodName);
		
	}

}
